package main
import (
	"bufio"
	"crypto/tls"
	"log"
	"net"
	"io"
)

/*
  go run $GOROOT/src/crypto/tls/generate_cert.go --host localhost
*/
func main() {
	//加载证书
	cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
	if err != nil {
		log.Println(err)
		return
	}
	//配置证书
	config := &tls.Config{Certificates: []tls.Certificate{cert}}
	//监听tcp tls
	ln, err := tls.Listen("tcp", ":8443", config)
	if err != nil {
		log.Println(err)
		return
	}
	defer ln.Close()
	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Println(err)
			continue
		}
		go handleServerConn(conn)
	}
}
func handleServerConn(conn net.Conn) {
	defer conn.Close()
	r := bufio.NewReader(conn)
	for {
		msg, err := r.ReadString('\n')
		if err != nil && err == io.EOF {
			log.Println(err)
			return
		}
		println(msg)
		n, err := conn.Write([]byte("world\n"))
		if err != nil {
			log.Println(n, err)
			return
		}
	}
}